#coding:utf-8
import sys,io,re,os,time,threading,thread
from day_log import log_set
#git pull .if has new,reboot RUN. 
#=========================#===================#==========================================================#
# check_by_git_and_reboot # 'name' 'run_path' # if git pull change, will CD to 'run_path',and run 'name' # 
# kill_runner             # 'name'            # kill -9 which has 'name'                                 #
# reboot_runner           # 'name' 'run_path' # CD to 'run_path' and run 'name'                          #
#=========================#===================#==========================================================#

def check_by_git_and_reboot(name,run_path='.'):
    line= os.popen('git pull').readlines()
    log_set(str(line))
    try:
        if 'Already up-to-date.' in line[0]:
            log_set('Git not change')
        else:
            log_set('Git change')
            kill_runner(name)
            time.sleep(5)#if not sleep,sometimes will kill the new run.
            reboot_runner(name,run_path)
    except Exception as e:
        log_set(str(e))
        #there is network error

#kill the RUN
def kill_runner(name): 
    #order = 'ps aux|grep %s|grep -v grep|awk "{print $2}"|xargs kill -9'%name
    #order = "ps x|grep %s|grep -v grep |awk '{print $1}'|xargs kill -9"%name
    order = "ps x|grep %s|grep -v grep |grep -v Reboot.py |awk '{print $1}'|xargs kill -9"%name
    os.system(order)
    log_set('kill [%s] is ok'%name)

#reboot the RUN
def reboot_runner(name,run_path='.'):
    order = 'cd %s'%run_path
    code = os.system(order)
    if code:
        log_set('run path is unknow')
        return False
    log_set('cd %s ok'%run_path)
    #t = threading.Thread(target=runner,args=(name,))
    #t.start()
    #time.sleep(2)
    #kill_self()

#def runner(name):
    order = 'python %s'%name
    os.system(order)
    log_set('run stop')

#def kill_self():
#    order = "ps x|grep Reboot.py|grep -v grep |awk '{print $1}'|xargs kill -9"
#    os.system(order)

if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print('''CheckAndReboot [run name] [run path] [force(not must)]
run name        : is you main file name
run path        : is you run path. If '.',it meat on this path. If './abc' it meat CD to 'abc' dir.
force(not must) : if had running,you should not give. if something at here, it meat only reboot.''')
        print('For exmaple: python CheckAndReboot.py run.py . 1')
    elif len(sys.argv)==3:
        print ('check and reboot!!!')
        check_by_git_and_reboot(sys.argv[1],sys.argv[2])
    else:
        print ('force run it!!!')
        reboot_runner(sys.argv[1],sys.argv[2])

